<template>
  <!--视频组件-->
  <div class="video-carousel">
    <div class="carousel">
      <div class="carousel-inner">
        <!--循环输出视频-->
        <!--通过判断 active: index === activeIndex 添加css样式-->
        <div
          v-for="(video, index) in videos"
          :key="index"
          :class="['carousel-item', { active: index === activeIndex }]"
        >
          <!-- autoplay自动播放 -->
          <video
            :src="video.url"
            ref="videoPlayer"
            :style="{ width: parentWidth + 'px', height: parentHeight + 'px' }"
            controls
            autoplay
            muted
            @ended="nextVideo, restartVideo"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "VideoCarousel",
  data() {
    return {
      /*索引*/
      activeIndex: 0,
    };
  },
  /*接收父元素传递参数*/
  props: {
    videos: {
      type: Array,
      required: true,
    },
    parentWidth: {
      type: Number,
      required: true,
    },
    parentHeight: {
      type: Number,
      required: true,
    },
  },
  mounted() {
    this.startAutoplay();
  },
  methods: {
    /*每个视频播放3秒*/
    startAutoplay() {
      setInterval(() => {
        this.nextVideo();
      }, 3000); // 自动播放间隔时间为3秒
    },
    /*切换下一个视频*/
    nextVideo() {
      this.activeIndex = (this.activeIndex + 1) % this.videos.length;
    },
    restartVideo() {
      const videoPlayer = this.$refs.videoPlayer;
      videoPlayer.currentTime = 0; // 重置视频播放时间为0
      videoPlayer.play(); // 重新播放视频
    },
  },
};
</script>

<style scoped>
.video-carousel {
  position: relative;
}

.video-carousel {
  position: relative;
}

.carousel {
  width: 100%;
  height: auto;
  overflow: hidden;
}

.carousel-inner {
  width: 400%; /* 设置为视频数量的四倍，以容纳所有视频 */
  height: 100%;
  display: flex;
  transition: transform 0.3s;
}

.carousel-item {
  flex: 0 0 25%; /* 设置为 100% / 视频数量，以平均分配宽度 */
}

.carousel-item.active {
  transform: translateX(0); /* 每次切换一个视频的宽度 */
}
video::-webkit-media-controls {
  display: none; /* 隐藏视频进度条 */
}
</style>
